<?php
// 本类由系统自动生成，仅供测试用途
namespace Backend\Controller;
use MyBase\BaseController;
use MyBase\Tool;
class IndexController extends BaseController {

    //检查是否登录
    public function _before_index(){
//     	session("admin",null);
        if(!session("admin")){
            $this->redirect('adminLogin');
        }
        //看是否曾经记住过
        if(cookie("admin_cookie")){
            $cookieData = cookie("admin_cookie");
            $cookieData['Password'] = base64_decode($cookieData['Password']);
            $this->assign("admin_cookie",$cookieData);
        } 
    }

    public function index(){
    	$cookPageLimit = 3;
    	$count = $this->CookBookModel->count();
    	$Page = new \Think\Page($count,$cookPageLimit);
    	$show = $Page->show();
    	$data = $this->CookBookModel->page(1,$cookPageLimit)->select();
        // print_r($data);
    	$this->assign('cookbook_data',$data);
    	$this->assign('cookbook_page',$show);
        //获取关于我们的数据
        $aboutUsData = $this->AboutModel->getAboutUsData();
        $this->assign('about_us_data',$aboutUsData);
    	$this->display();
    }
    
    public function ajaxGetCookBookPageData(){
    	$cookPageLimit = 3;
    	$postData = I("get.");//page_num
    	$count = $this->CookBookModel->count();
    	$Page = new \Think\Page($count,$cookPageLimit);
    	$show = $Page->show();
    	$data = $this->CookBookModel->page($postData['p'],$cookPageLimit)->select();
    	$this->assign('cookbook_data',$data);
    	$this->assign('cookbook_page',$show);
    	layout(false);
    	$this->display("index/cookbook_page");    	
    }
    public function adminLogin(){
    	if(cookie("admin_cookie")){
            $cookieData = cookie("admin_cookie");
            $cookieData['Password'] = base64_decode($cookieData['Password']);
    		$this->assign("admin_cookie",$cookieData);
    	}  
        $this->display();
    }
    public function checkAdminLogin(){
    	$postData = I("post.");
    	if(Tool::isEmail($postData['UserName'])){
    		//Is email
    		$res = $this->UserModel->getUserInfoByUserEmail($postData['UserName'],false);
    	}else{
    		//Is userName
    		$res = $this->UserModel->getUserInfoByUserName($postData['UserName'],false);
    	}
    	if(!$res){
    		$this->ajaxReturn(false,'用户不存在 !');
    	}
    	if($res['flag'] != "Y"){
    		$this->ajaxReturn(false,'请以管理员身份登录！');
    	}
    	if(md5(md5($postData['Password']).$res['salt']) != $res['password']){
    		$this->ajaxReturn(false,'密码错误 !');
    	}
		if($postData['DropExpiration'] != 0){
			$days = $postData['DropExpiration'];
			unset($postData['DropExpiration']);
            $postData['Password'] = base64_encode($postData['Password']);
			cookie('admin_cookie',$postData,$days*24*3600);
		}
		
    	session("admin",$res);
    	$this->ajaxReturn(true,'成功登陆!');
    }
    
    public function adminLoginOut(){
    	session('admin',null);
    	$this->ajaxReturn(true);
    }
    //ajax上传菜谱图片
    public function ajaxUploadCookFoodImg(){
        $upload = new \Think\Upload();
        $upload->maxSize = 2097152;
        $upload->exts = array('jpg', 'gif', 'png', 'jpeg');
        $upload->subName = "temp";
        $info = $upload->upload();

        if(!$info){
            $this->ajaxReturn(false,'上传失败',$upload->getError());
        }
        $this->ajaxReturn(true,'上传成功',$info['Filedata']);
    }

    //cookbook上传
    public function ajaxCookBookRegister(){
        $postData = I('post.');
        foreach ($postData as $key => $value) {
            if($key == 'editorValue'){
                $postData['cookbook_content'] = $value;
                unset( $postData[$key]);
            }
        }
        $postData['cookbook_add_time'] = time();
        $addRes = $this->CookBookModel->data($postData)->filter('strip_tags')->add();//返回插入记录的id

        // print_r($cookBook->getLastSql());
        // 插入成功，转义图片,图片所在文件夹是add_time字段
        $tempImgPath  = './Uploads/temp/'.$postData['cookbook_photo'];
        if(!file_exists($tempImgPath)){
            $this->ajaxReturn(false,'图片丢失');
        }
        $newImgPath = './Uploads/cookbook/'.$postData['cookbook_add_time'].$addRes.'/'.$postData['cookbook_photo'];
        $this->copy_move($tempImgPath,$newImgPath);
        if(!$addRes){
            $this->ajaxReturn(false,'插入失败');
        }
        $this->ajaxReturn(true,'插入成功');
    }
    /**
     * [copy_move 移动文件]
     * @param  [type] $src  [description]
     * @param  [type] $dest [description]
     * @return [type]       [description]
     */
    public function copy_move($src,$dest){
        $dir = dirname($dest);
        if(!file_exists($dir)){
            $this->createDir($dir);
        }
        rename($src,$dest);
    }
    /**
     * [createDir 创建目录]
     * @param  [type] $path [description]
     * @return [type]       [description]
     */
    public function createDir($path){ 
        if (!file_exists($path)){ 
            $this->createDir(dirname($path)); 
            mkdir($path, 0777); 
        }
    }

    /**
     * 菜谱删除，传入的Id可能是单个Id，也可能是一个数组
     * 
     */
    public function ajaxDelCookbook(){
        $postData = I('post.');
        $delRes = $this->CookBookModel->cookbookDel($postData['cookbook_id']);
        if($delRes === false){
            $this->ajaxReturn(false,'操作失败');
        }
        $this->ajaxReturn(true,'操作成功！',$postData['cookbook_id']);
    }

    /**
     * 菜谱禁用，传入的Id可能是单个Id，也可能是一个数组
     * 
     */
    public function ajaxForbiddenCookbook(){
        $postData = I('post.');
        $delRes = $this->CookBookModel->cookbookForbidden($postData['cookbook_id']);
        if($delRes === false){
            $this->ajaxReturn(false,'操作失败');
        }
        $this->ajaxReturn(true,'操作成功！',$postData['cookbook_id']);       
    }

    /**
     * 菜谱恢复，传入的Id可能是单个Id，也可能是一个数组
     * 
     */
    public function ajaxRecoverCookbook(){
        $postData = I('post.');
        $delRes = $this->CookBookModel->cookbookRecover($postData['cookbook_id']);
        if($delRes === false){
            $this->ajaxReturn(false,'操作失败');
        }
        $this->ajaxReturn(true,'操作成功！',$postData['cookbook_id']);       
    }
    /**
     * [ajaxGetCookbookEditPage 进入菜谱编辑选项卡]
     * @return [type] [description]
     */
    public function ajaxGetCookbookEditPage(){
        layout(false);
        $postData = I('post.');
        $editData = $this->CookBookModel->getCookbookInfoById($postData['cookbook_id']);
        $editData['cookbook_photo_src'] = __ROOT__.'/Uploads/cookbook/'.$editData['cookbook_add_time'].$editData['cookbook_id'].'/'.$editData['cookbook_photo'];
        $this->assign('edit_data',$editData);
        $this->display("Index/cookbook_edit_page");
    }

    /**
     * 保存编辑
     */
    public function ajaxSaveCookcookEdit(){
        $postData = I('post.');
        // print_r($postData);
        $data['cookbook_name'] = $postData['cookbook_eidt_name'];
        $data['cookbook_material'] = $postData['cookbook_eidt_material'];
        $data['cookbook_description'] = $postData['cookbook_eidt_description'];
        if($postData['cookbook_eidt_photo'] ==''){
            unset($postData['cookbook_eidt_photo']);
        }else{
           $data['cookbook_photo'] = $postData['cookbook_eidt_photo']; 
            //如果图片呗修改，则移动图片
            $tempImgPath  = './Uploads/temp/'.$postData['cookbook_eidt_photo'];
            if(!file_exists($tempImgPath)){
                $this->ajaxReturn(false,'图片丢失');
            }
            $editData = $this->CookBookModel->getCookbookInfoById($postData['cookbook_edit_id']);
            $newImgPath = './Uploads/cookbook/'.$editData['cookbook_add_time'].$editData['cookbook_id'].'/'.$postData['cookbook_eidt_photo'];
            // echo $newImgPath;
            $this->copy_move($tempImgPath,$newImgPath);
        }
        $res = $this->CookBookModel->updateCookbookById($postData['cookbook_edit_id'],$data);
        if($res === false){
            $this->ajaxReturn(false,'更新失败!');
        }
        $this->ajaxReturn(true,'更新成功!');
    }

    /**
     * 异步更新关于我们的数据
     */
    public function ajaxUpdateAboutUsData(){
        $postData = I('post.');
        // print_r($postData);
        $res = $this->AboutModel->updateAboutUsData($postData['content']);
        // var_dump($res);
        if($res === false){
            $this->ajaxReturn(false,'更新失败！');
        }
        $this->ajaxReturn(true,'更新成功！');
    }

    public function movePic($picName,$addTime,$id,$desDirName){
        $tempImgPath  = './Uploads/temp/'.$picName;
        if(!file_exists($tempImgPath)){
            return false;
        }
        $newImgPath = './Uploads/'.$desDirName.'/'.$addTime.$id.'/'.$picName;
        // echo $newImgPath;
        $this->copy_move($tempImgPath,$newImgPath);  
        return true;      
    }

    //异步加载用户管理列表
    //会有管理与普通用户的区别
    //页数的接收
    public function ajaxLoadUserList(){
        layout(false);
        $postData = I("get.");//page_num
        //显示分页 
        $pageNum = 5;//每页显示的条数
        //查询总条数
        $count = $this->UserModel->where("flag = '{$postData['flag']}'" )->count();
        $page = new \Think\Page($count,$pageNum);
        $show = $page->show();
        $this->assign('user_page',$show);
        $data = $this->UserModel->where("flag = '{$postData['flag']}'")->page($postData['p'],$pageNum)->select();
        $this->assign('user_data',$data);
        if($postData['flag'] == 'Y'){
            $this->assign('user_form_name','admin_mutil_operate');
            $this->assign('user_table_name','admin_list');
            $this->assign('user_checkbox_name','admin_all');
        }else{
            $this->assign('user_form_name','user_mutil_operate');
            $this->assign('user_table_name','user_list');
            $this->assign('user_checkbox_name','user_all');
        }
        $this->display('Index/user_list_page');
    }

    public function ajaxUserDelete(){
        $postData = I("post.");
        $res = $this->UserModel->userDelete($postData['user_id']);
        if(!$res){
            $this->ajaxReturn(false,'删除失败');
        }
        $this->ajaxReturn(true,'删除成功',$postData['user_id']);
    }

    public function ajaxLoadAdminRegister(){
        layout(false);
        $this->display("Index/admin_register");
    }

    /**
     * 检测用户名是否唯一
     */
    public function ajaxCheckNameUnique(){
        $userName = I('post.name');
        $res = $this->UserModel->checkUserNameUnique($userName);
        if(!$res){
            $this->ajaxReturn(true,'用户可以注册');
        }
        $this->ajaxReturn(false,'用户名已被注册');
    }
    /**
     * 检测邮箱是否唯一
     */
    public function ajaxCheckEmailUnique(){
        $userEmail = I('post.email');
        $res = $this->UserModel->checkEmailUnique($userEmail);
        // var_dump($res);
        if(!$res){
            $this->ajaxReturn(true,'邮箱可以使用');
        }
        $this->ajaxReturn(false,'邮箱已被注册');
    }
    /**
     * 生成盐
     * 
     */
    private function produceSalt(){
        return mt_rand(1000,99999);
    }

    public function registerAdmin(){
        $postData = I("post.");
        if($postData['password'] != $postData['repassword']){
            $this->ajaxReturn(false,'两次密码不一致');
        }
        unset($postData['repassword']);

        $postData['salt'] = $this->produceSalt();
        $postData['password'] = md5(md5($postData['password']).$postData['salt']);
        $postData['flag'] = 'Y';
        $res = $this->UserModel->data($postData)->add();
        if(!$res){
            $this->ajaxReturn(false,'注册失败了');
        }
        $this->ajaxReturn(true,'恭喜您注册成功');
    }
}